package com.zb.jnlxc.service;

import com.ZLHW.base.Exception.BaseErrorModel;
import com.ZLHW.base.Form.Page;
import com.ZLHW.base.dao.QueryCondition;
import com.ZLHW.base.service.BaseService;
import com.zb.jnlxc.dao.*;
import com.zb.jnlxc.form.ProductTrace;
import com.zb.jnlxc.model.*;
import com.zb.util.StringUtils;
import net.sf.jasperreports.engine.JRException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentException;
import org.jbpm.api.Execution;
import org.jbpm.api.ProcessInstance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Transactional
@Service
public class PaichanRecordService extends BaseService<PaiChanRecordDAO,PaiChanRecord, Integer> {
	private static final Log log = LogFactory.getLog(PaichanRecordService.class);
	@Resource
	private OrderFormDAO orderFormDAO;
	@Resource
	private ReportService reportService;
	@Resource
	private OrderDetailDAO orderDetailDAO;
    @Resource
    private PaichanOrderDetailDAO paichanOrderDetailDAO;
    @Resource
    private ProductProcessDAO productProcessDAO;

	@Value("${print.server.url}")
	private String printServerUrl;
	@Value("${print.server.port}")
	private int printServerPort;
	@Resource
	FlowService flowService;
    @Resource
    AdminDAO adminDAO;

	/**
	 * 通过任务id查询生产记录
	 * @param taskId
	 * @return
	 */
	public PaiChanRecord getPaiChanRecordByTaskId(String taskId){
		Integer paichanRecordId = (Integer) flowService.getContentMap(taskId, "paichanRecordId");
		return this.getById(paichanRecordId);
	}

    public List<ProductTrace> getProductTrace(String taskId){
        PaiChanRecord paiChanRecord = getPaiChanRecordByTaskId(taskId);
        OrderForm orderForm = paiChanRecord.getOrderForm();
        List<PaichanOrderDetail> paichanOrderDetailList =
                paichanOrderDetailDAO.findByPaichan(paiChanRecord.getDbId());

        List<ProductTrace> results = new ArrayList<ProductTrace>();

        for (PaichanOrderDetail paichanOrderDetail:paichanOrderDetailList){
            ProductTrace productTrace = new ProductTrace();
            productTrace.setFinishQuantiy(paichanOrderDetail.getCompQuantity());
            productTrace.setFinishWeight(paichanOrderDetail.getCompWeight());
            OrderDetail orderDetail = paichanOrderDetail.getOrderDetail();
            productTrace.setAginghardness(paiChanRecord.getAginghardness());
            productTrace.setOxideFilm(orderForm.getOxideFilm());
            productTrace.setAlHeatNum(paiChanRecord.getAlHeatNum());
            productTrace.setOrderQuantity(paichanOrderDetail.getOrderQuantity());
            productTrace.setOrderWeight(paichanOrderDetail.getOrderWeight());
            productTrace.setUncompleteQuantity(paichanOrderDetail.getOrderQuantity()-paichanOrderDetail.getCompQuantity());
            productTrace.setUncompleteWeight(paichanOrderDetail.getOrderWeight()-paichanOrderDetail.getCompWeight());
            productTrace.setDbId(orderDetail.getDbId());
            productTrace.setOrderDetail(orderDetail);
            productTrace.setSetSize(orderDetail.getSetSize());
            productTrace.setAlHeatNum(paiChanRecord.getAlHeatNum());
            productTrace.setPack(orderDetail.getOrderForm().getPack());
            productTrace.setPreSendDate(orderDetail.getOrderForm().getPreSendDate());
            productTrace.setEnough(orderDetail.getCompStatus());
            results.add(productTrace);
        }
        return results;
    }

	/**
	 * 分页载入生产记录
	 * @param page
	 * @return
	 */
	public Page loadProductRecordByPage(Page page) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<QueryCondition> queryConditions=new ArrayList();
        StringBuilder hql = new StringBuilder("from PaiChanRecord t where 1=1 ");
        if (StringUtils.isNotEmpty(page.getParameter("orderId"))){
            Integer orderId = Integer.parseInt(page.getParameter("orderId"));
            hql.append("and t.orderForm.dbId = :orderId ");
            queryConditions.add(new QueryCondition("orderId", orderId));
        }
        if (StringUtils.isNotEmpty(page.getParameter("code"))){
            hql.append("and t.code like :code ");
            queryConditions.add(new QueryCondition("code", "%"+page.getParameter("code")+"%"));
        }
        if (StringUtils.isNotEmpty(page.getParameter("orderCode"))){
            hql.append("and t.orderForm.code like :orderCode ");
            queryConditions.add(new QueryCondition("orderCode", "%"+page.getParameter("orderCode")+"%"));
        }
        if(StringUtils.isNotEmpty(page.getParameter("startDate"))){
            hql.append("and t.createDate >=:startDate ");
            Date startDate=sdf.parse(page.getParameter("startDate"));
            queryConditions.add(new QueryCondition("startDate", startDate));
        }
        if(StringUtils.isNotEmpty(page.getParameter("endDate"))){
            hql.append("and t.createDate <:endDate ");
            Date endDate=sdf.parse(page.getParameter("endDate"));
            queryConditions.add(new QueryCondition("endDate", endDate));
        }
        hql.append("order by ").append(page.getSortKey()).append(" ").append(page.getSortOrder());
        this.getDao().findByPageWithTmpHQL(page, hql.toString(), queryConditions);
		return page;
	}

    public void checkOrderState(String taskId){
        OrderForm orderForm = getOrderFormInfo(taskId);
        if(orderForm.getCurrentState()==2)
            throw new BaseErrorModel("流程暂停，无法操作", "");
    }

    public void updateOrderMcomment(String taskId,String wcomment){
        OrderForm orderForm = getOrderFormInfo(taskId);
        orderForm.setMcomment(wcomment);
        orderFormDAO.update(orderForm);
    }
	/**
	 * 从流程中取得订单信息
	 * @param taskId
	 * @return
	 */
	public OrderForm getOrderFormInfo(String taskId){
		Integer orderFormId=(Integer)flowService.getContentMap(taskId, "orderFormId");
		return orderFormDAO.getById(orderFormId);
	}


	/**
	 * 打印生产跟踪单并开启流程，保存生产记录
	 * @param taskId
	 * @return
	 * @throws net.sf.jasperreports.engine.JRException
	 * @throws com.ZLHW.base.Exception.BaseErrorModel
	 */
	public void printForm(String taskId,String comment,Admin user) throws JRException, BaseErrorModel  {
        updateOrderMcomment(taskId,comment);
		flowService.completeTask(taskId,user);
	}

	/**
	 * 输出PDF流
	 * @param taskId
	 * @throws net.sf.jasperreports.engine.JRException
	 * @throws org.dom4j.DocumentException
	 */
	public void startCreatePDF(String taskId,OutputStream os) throws JRException, DocumentException{
        PaiChanRecord paiChanRecord = getPaiChanRecordByTaskId(taskId);
		reportService.exportProductRecord(paiChanRecord,os);
	}
	//生产部审核
	public void productionAudit(String taskId,String wcomment,Admin user) throws BaseErrorModel{
        updateOrderMcomment(taskId,wcomment);
		flowService.completeTask(taskId,user);
	}


	/**
	 * 删除生产记录的同时，更新订单以及订单明细
	 */
	public void delete(PaiChanRecord paiChanRecord) throws BaseErrorModel{
        flowService.deleteProcessInstanceCascade("productRecordFlow."+paiChanRecord.getCode());
        delete(paiChanRecord);
	}
	/**
	 * 删除正在执行的跟踪单流程
	 * @param id
	 * @throws com.ZLHW.base.Exception.BaseErrorModel
	 */
	public void deleteProductFlowInstanceCascade(String id) throws BaseErrorModel{
		Execution execution=flowService.getExecutionService().findExecutionById(id);
		Integer paichanRecordId=(Integer) flowService.getExecutionService().getVariable(id, "paichanRecordId");
		if(paichanRecordId!=null){
		PaiChanRecord paiChanRecord=this.getById(paichanRecordId);
		if(paiChanRecord!=null){
			this.delete(paiChanRecord);
		}
		}
		flowService.deleteProcessInstanceCascade(id);
	}

	/**
	 * 发布一个跟踪单流程图(流程版本，只发布一次，平常不用)
	 * 流程图jpdl位置（比如"./com/zb/JBPM/orderFlow.jpdl.xml"）
	 * @return
	 */
	public String deployFlow() {
		String path = "./com/zb/JBPM/productRecordFlow.jpdl.xml";
		return flowService.getRepositoryService().createDeployment()
				.addResourceFromClasspath(path).deploy();
	}
	
	/**
	 * 用于前台获取跟踪单信息
	 * @param taskId
	 * @return
	 */
	public Map getProductRecordInfo(String taskId){
        PaiChanRecord paiChanRecord = getPaiChanRecordByTaskId(taskId);
		OrderForm orderForm=paiChanRecord.getOrderForm();

		Map map=new HashMap();
		map.put("orderForm", orderForm);
		map.put("productTeamId",paiChanRecord.getProductTeam().getDbId());
		map.put("productNum", orderForm.getNextRecordNum());
		map.put("productCode", paiChanRecord.getCode());
		map.put("productRecord", paiChanRecord);
		return map;
	}

	/**
	 * 找到当前的流程实例
	 * 
	 * @param id
	 * @return
	 */
	public ProcessInstance findProductRecordFlowInstanceByKey(String id) {
		return flowService.findProcessInstanceByKey("productRecordFlow", id);
	}


    public List<PaichanOrderDetail> getPaichanDetails(Integer paiChanRecordId) {
        return paichanOrderDetailDAO.findByPaichan(paiChanRecordId);
    }

}
